package com.chenfeilin.producer.WorkQueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class Producer_WorkQueue {

    public static void main(String[] args) throws
            IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException {

        // 第一种方式，方法设定参数

        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 主机地址: 默认为 localhost
        connectionFactory.setHost("localhost");
        // 连接端口: 默认为 5672
        connectionFactory.setPort(5672);
        // 虚拟主机名称: 默认为 /
        connectionFactory.setVirtualHost("/test");
        // 连接用户名: 默认为guest
        connectionFactory.setUsername("cfl");
        // 连接密码: 默认为guest
        connectionFactory.setPassword("cfl");
        // 从工厂获得连接：
        Connection connection = connectionFactory.newConnection();

        // 第二种方式，使用URL方式
        /*ConnectionFactory connectionFactoryForURL = new ConnectionFactory();
        connectionFactoryForURL.setUri("amqp://userName:password@ipAddress:portNumber/virtualHost");*/

        // 用连接创建Channel
        Channel channel = connection.createChannel();

        // 声明一个队列
        channel.queueDeclare("Work_Queue", false, false, false, null);
        String message = "work queue ";
        for (int i = 0; i < 10; i++) {
            channel.basicPublish("", "Work_Queue", null, (message + i).getBytes());
            System.out.println(" [x] Sent '" + (message + i) + "'");
        }

        // 关闭资源
        channel.close();
        connection.close();

    }


}
